package com.qs.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.PhoneUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qs.constant.LoginConstant;
import com.qs.constant.RedisConstant;
import com.qs.constant.StatusConstant;
import com.qs.exception.ServiceException;
import com.qs.pojo.dto.AdminDto;
import com.qs.pojo.dto.UserDto;
import com.qs.pojo.entity.Admin;
import com.qs.pojo.entity.User;
import com.qs.mapper.UserMapper;
import com.qs.pojo.vo.PasswordVo;
import com.qs.pojo.vo.PersonalVo;
import com.qs.pojo.vo.UserVo;
import com.qs.response.Response;
import com.qs.response.ResponseEnum;
import com.qs.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qs.utils.EncryptUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 普通用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-11-12
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final RedisTemplate redisTemplate;

    @Override
    public Map<String, Object> getList(Integer pageNo, Integer pageSize, UserVo userVo) {
        //去除前后空白
        String trimName = userVo.getName().trim();
        String trimRole = userVo.getRole().trim();
        Page<User> pageInfo = new Page<>(pageNo,pageSize);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        /**
         * 根据用户名进行模糊查询
         */
        wrapper.eq(!StringUtils.isBlank(trimName),"name",trimName);
        wrapper.eq(!StringUtils.isBlank(trimRole),"role",trimRole);
        wrapper.orderByDesc("update_time");
        Page<User> userPage = baseMapper.selectPage(pageInfo, wrapper);
        if(null != userPage) {
            //进行数据转换
            List<User> records = userPage.getRecords();
            List<UserDto> adminDtoList = new ArrayList<>();
            records.stream().forEach(item -> {
                UserDto userDto = new UserDto();
                BeanUtils.copyProperties(item,userDto);
                userDto.setKey(item.getId());
                adminDtoList.add(userDto);
            });
            Map<String,Object> map = new HashMap<>();
            map.put("data",adminDtoList);
            map.put("total",userPage.getTotal());
            return map;
        }
        return null;
    }

    @Override
    public void updateByKey(UserDto userDto) {
        boolean validCard = IdcardUtil.isValidCard(userDto.getIdCard());
        /**
         * 身份证是否合法
         */
        if(!validCard) {
            throw new ServiceException(ResponseEnum.ID_CARD_ILLEGAL);
        }
        /**
         * 手机号是否合法
         */
        if(!PhoneUtil.isPhone(userDto.getPhone())){
            throw new ServiceException(ResponseEnum.PHONE_ILLEGAL);
        }
        /**
         * 用户昵称是否唯一
         */
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq(!StringUtils.isEmpty(userDto.getNickName()),"nick_name",userDto.getNickName());
        User userOne = baseMapper.selectOne(wrapper);
        if(null != userOne){
            throw new ServiceException(ResponseEnum.NICK_NAME_EXITS);
        }
        /**
         * 一个身份证号只能查出一个用户
         */
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(!StringUtils.isEmpty(userDto.getIdCard()),"id_card",userDto.getIdCard());
        List<User> userList = baseMapper.selectList(wrapper);
        if(userList.size() > 1) {
            throw new ServiceException(ResponseEnum.ID_CARD_USED);
        }
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        user.setId(userDto.getKey());
        baseMapper.updateById(user);
    }

    @Override
    public UserDto echo(Integer id) {
        if(null != id) {
            User user = baseMapper.selectById(id);
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user,userDto);
            userDto.setKey(user.getId());
            return userDto;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatchByIds(List<Integer> ids) {
        List<User> userList = baseMapper.selectBatchIds(ids);
        //查询状态是否有正常的用户
        if(!CollectionUtils.isEmpty(userList)){
            //如果有 需禁用才能删除
            List<User> list = userList.stream().filter(item -> item.getStatus().getComment().equalsIgnoreCase(StatusConstant.STATUS_NORMAL)).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(list)){
                throw new ServiceException(ResponseEnum.ADMIN_NORMAL);
            }
            //进行删除操作
            baseMapper.deleteBatchIds(ids);
        }
    }

    @Override
    public void saveUser(User user) {
        boolean validCard = IdcardUtil.isValidCard(user.getIdCard());
        /**
         * 身份证是否合法
         */
        if(!validCard) {
            throw new ServiceException(ResponseEnum.ID_CARD_ILLEGAL);
        }
        /**
         * 手机号是否合法
         */
        if(!PhoneUtil.isPhone(user.getPhone())){
            throw new ServiceException(ResponseEnum.PHONE_ILLEGAL);
        }
        /**
         * 用户昵称是否唯一
         */
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq(!StringUtils.isEmpty(user.getNickName()),"nick_name",user.getNickName());
        User userOne = baseMapper.selectOne(wrapper);
        if(null != userOne){
            throw new ServiceException(ResponseEnum.NICK_NAME_EXITS);
        }
        /**
         * 一个身份证号只能查出一个用户
         */
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(!StringUtils.isEmpty(user.getIdCard()),"id_card",user.getIdCard());
        User userCard = baseMapper.selectOne(queryWrapper);
        if(null != userCard) {
            throw new ServiceException(ResponseEnum.ID_CARD_USED);
        }
        /**
         * 一个手机号只能查出一个用户
         */
        QueryWrapper<User> phoneWrapper = new QueryWrapper<>();
        phoneWrapper.eq(!StringUtils.isEmpty(user.getIdCard()),"phone",user.getPhone());
        User userPhone = baseMapper.selectOne(queryWrapper);
        if(null != userPhone) {
            throw new ServiceException(ResponseEnum.PHONE_EXITS);
        }
        baseMapper.insert(user);
    }

    @Override
    public UserDto certification(User user) {
        /**
         * 身份证是否合法
         */
        if(!IdcardUtil.isValidCard(user.getIdCard())) {
            throw new ServiceException(ResponseEnum.ID_CARD_ILLEGAL);
        }
        /**
         * 一个身份证号只能查出一个用户
         */
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(!StringUtils.isEmpty(user.getIdCard()),"id_card",user.getIdCard());
        User userCard = baseMapper.selectOne(queryWrapper);
        if(null != userCard) {
            throw new ServiceException(ResponseEnum.ID_CARD_USED);
        }
        /**
         * 手机号是否合法
         */
        if(!StringUtils.isEmpty(user.getPhone())){
            if(!PhoneUtil.isPhone(user.getPhone())){
                throw new ServiceException(ResponseEnum.PHONE_ILLEGAL);
            }
            /**
             * 一个手机号只能查出一个用户
             */
            QueryWrapper<User> phoneWrapper = new QueryWrapper<>();
            phoneWrapper.eq(!StringUtils.isEmpty(user.getIdCard()),"phone",user.getPhone());
            User userPhone = baseMapper.selectOne(phoneWrapper);
            if(null != userPhone) {
                throw new ServiceException(ResponseEnum.PHONE_EXITS);
            }
        }
        User userOne = baseMapper.selectById(user.getId());
        //这种情况是此用户先前拿手机号注册，现在补充一下字段
        if(StringUtils.isEmpty(user.getPhone())) {
            userOne.setName(user.getName());
            userOne.setIdCard(user.getIdCard());
            userOne.setSex(user.getSex());
            userOne.setAddress(user.getAddress());
            if(!StringUtils.isBlank(user.getNickName())){
                userOne.setNickName(user.getNickName());
            }
        }else if(StringUtils.isEmpty(user.getNickName())) {
            userOne.setName(user.getName());
            userOne.setIdCard(user.getIdCard());
            userOne.setSex(user.getSex());
            userOne.setAddress(user.getAddress());
            if(!StringUtils.isBlank(user.getPhone())){
                userOne.setPhone(user.getPhone());
            }
        }else{
            userOne.setName(user.getName());
            userOne.setIdCard(user.getIdCard());
            userOne.setSex(user.getSex());
            userOne.setAddress(user.getAddress());
        }
        //认证过后角色一律设置为商户
        userOne.setRole(LoginConstant.ROLE_BUSINESS);
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(userOne,userDto);
        userDto.setKey(userOne.getId());
        baseMapper.updateById(userOne);
        return userDto;
    }

    @Override
    public void updatePassword(PasswordVo passwordVo) {
        User user = baseMapper.selectById(passwordVo.getId());
        if(StringUtils.isBlank(user.getPassword())){
            throw new ServiceException(ResponseEnum.PASSWORD_NULL);
        }
        //将老密码加密与数据库中的密码比对
        if(!user.getPassword().equalsIgnoreCase(EncryptUtils.MD5Password(passwordVo.getOldPassword()))){
            throw new ServiceException(ResponseEnum.PASSWORD_OLD_ERROR);
        }
        //将新密码加密保存到数据中
        user.setPassword(EncryptUtils.MD5Password(passwordVo.getNewPassword()));
        baseMapper.updateById(user);
    }

    @Override
    public void updatePersonal(PersonalVo personalVo) {
        //检验验证码是否过期
        String code = (String) redisTemplate.opsForValue().get(RedisConstant.MESSAGE_CODE + personalVo.getPhone());
        if(StringUtils.isEmpty(code)){
            throw new ServiceException(ResponseEnum.CODE_TIMEOUT);
        }
        //对比验证码是否正确
        if(!personalVo.getCode().equalsIgnoreCase(code)){
            throw new ServiceException(ResponseEnum.CODE_ERROR);
        }
        /**
         * 昵称是否重名
         */
        if(!StringUtils.isEmpty(personalVo.getNickName())){
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("nick_name",personalVo.getNickName());
            User selectOne = baseMapper.selectOne(wrapper);
            if(null != selectOne){
                if(selectOne.getId().intValue() != personalVo.getId()){
                    throw new ServiceException(ResponseEnum.NICK_NAME_EXITS);
                }
            }
        }
        /**
         * 手机号是否已被注册
         */
        if(!StringUtils.isEmpty(personalVo.getNickName())){
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("phone",personalVo.getPhone());
            User selectOne = baseMapper.selectOne(wrapper);
            if(null != selectOne){
                if(selectOne.getId().intValue() != personalVo.getId()){
                    throw new ServiceException(ResponseEnum.PHONE_EXITS);
                }
            }
        }
        User user = baseMapper.selectById(personalVo.getId());
        String md5Password = "";
        if(!StringUtils.isBlank(personalVo.getPassword())){
            if(StringUtils.isBlank(user.getPassword())){
                md5Password = EncryptUtils.MD5Password(personalVo.getPassword());
            }else{
                if(!user.getPassword().equalsIgnoreCase(personalVo.getPassword())){
                    md5Password = EncryptUtils.MD5Password(personalVo.getPassword());
                }
            }
        }
        BeanUtils.copyProperties(personalVo,user);
        if(!StringUtils.isBlank(md5Password)){
            user.setPassword(md5Password);
        }
        baseMapper.updateById(user);
    }

    @Override
    public PersonalVo echoPersonal(Integer id) {
        User user = baseMapper.selectById(id);
        PersonalVo personalVo = new PersonalVo();
        BeanUtils.copyProperties(user,personalVo);
        return personalVo;
    }

    @Override
    public Map<String, Object> findRegisterUserNum() {
        //查询总注册的用户数量
        Long count = baseMapper.selectCount(null);
        //查询昨天注册的用户数量
        Long yesterdayNum = baseMapper.findRegisteYesterday();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("count", count);
        map.put("yesterday",yesterdayNum);
        return map;
    }

    @Override
    public Map<String, Object> findBusinessNum() {
        //查询总商户数量
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("role","商户");
        Long count = baseMapper.selectCount(wrapper);
        //查询昨天认证的商户数量
        Long yesterdayNum = baseMapper.findBusinessYesterday();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("count", count);
        map.put("yesterday",yesterdayNum);
        return map;
    }
}
